package com.mlink.ai.chat.utils

import android.Manifest
import android.app.*
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat.shouldShowRequestPermissionRationale
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import com.google.firebase.messaging.RemoteMessage
import com.mlink.ai.chat.assistant.robot.R
import com.mlink.ai.chat.assistant.robot.databinding.DialogNotificationPermissionBinding
import com.mlink.ai.chat.bean.ExploreSubCategory
import com.mlink.ai.chat.constants.EXTRA_FROM_PROMPT_NOTIFICATION
import com.mlink.ai.chat.constants.EXTRA_PROMPT_CATEGORY_EVENT_NAME
import com.mlink.ai.chat.constants.EXTRA_PROMPT_SUBCATEGORY_EVENT_NAME
import com.mlink.ai.chat.constants.KEY_CHAT_PROMPT
import com.mlink.ai.chat.ui.activity.ChatActivity
import com.mlink.ai.chat.ui.activity.SplashActivity
import com.tencent.mmkv.MMKV

class NotificationUtils(activity: AppCompatActivity) {

    private fun showNotificationPermissionRequestDialog(activity: Activity) {
        val lastDismissTime = MMKV.defaultMMKV().decodeLong(
            PREF_NOTIFICATION_PERMISSION_DIALOG_DISMISS_TIME, 0)
        val interval = System.currentTimeMillis() - lastDismissTime
        if (interval < ONE_DAY) {
            return
        }
        val binding = DialogNotificationPermissionBinding.inflate(LayoutInflater.from(activity))
        val dialog =
            AlertDialog.Builder(activity, R.style.CustomAlertDialogStyle).setView(binding.root)
                .create()
        dialog.setCancelable(false)
        dialog.show()
        dialog.setOnDismissListener {
            MMKV.defaultMMKV().encode(PREF_NOTIFICATION_PERMISSION_DIALOG_DISMISS_TIME, System.currentTimeMillis())
        }
        binding.tvAllow.setOnClickListener {
            AnalyticsEvents.AC_AUTH_PUSH_NOT_SEL.logEvent(
                Bundle().apply {
                    putString(AnalyticsParams.KEY_TYPE, AnalyticsParams.ALLOW)
                }
            )
            PermissionHelper.openAppSettings(activity)
            dialog.dismiss()
        }
        binding.tvCancel.setOnClickListener {
            AnalyticsEvents.AC_AUTH_PUSH_NOT_SEL.logEvent(
                Bundle().apply {
                    putString(AnalyticsParams.KEY_TYPE, AnalyticsParams.CANCEL)
                }
            )
            dialog.dismiss()
        }
        AnalyticsEvents.AC_AUTH_PUSH_NOT_SHOW.logEvent()
    }

    // Declare the launcher at the top of your Activity/Fragment:
    private val requestPermissionLauncher = activity.registerForActivityResult(
        ActivityResultContracts.RequestPermission(),
    ) { isGranted: Boolean ->
        if (isGranted) {
            AnalyticsEvents.AC_AUTH_PUSH_NOT_SUC.logEvent()
            // FCM SDK (and your app) can post notifications.
        } else {
            // TODO: Inform user that that your app will not show notifications.
        }
    }

    fun askNotificationPermission(activity: Activity) {
        if (!hasNotificationPermission(activity)) {
            // This is only necessary for API level >= 33 (TIRAMISU)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                if (shouldShowRequestPermissionRationale(
                        activity,
                        Manifest.permission.POST_NOTIFICATIONS
                    )
                ) {
                    // TODO: display an educational UI explaining to the user the features that will be enabled
                    //       by them granting the POST_NOTIFICATION permission. This UI should provide the user
                    //       "OK" and "No thanks" buttons. If the user selects "OK," directly request the permission.
                    //       If the user selects "No thanks," allow the user to continue without notifications.

                    showNotificationPermissionRequestDialog(activity)
                } else {
                    // Directly ask for the permission
                    requestPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
                }
            } else {
                showNotificationPermissionRequestDialog(activity)
            }
        }
    }

    companion object {

        private const val PREF_NOTIFICATION_PERMISSION_DIALOG_DISMISS_TIME =
            "notification_permission_dialog_dismiss_time"
        private const val ONE_DAY = 24 * 60 * 60 * 1000

        private const val FCM_NOTIFICATION_ID = 2
        private var promptLocalNotificationId = 3

        fun hasNotificationPermission(context: Context) =
            PermissionHelper.hasNotificationPermission(context)

        fun showFcmNotification(context: Context, remoteNotification: RemoteMessage.Notification) {
            if (!hasNotificationPermission(context)) {
                return
            }
            val notification = createFCMNotification(context, remoteNotification)
            val notificationManager = NotificationManagerCompat.from(context)
            notificationManager.notify(FCM_NOTIFICATION_ID, notification)
        }

        private fun createFCMNotification(
            context: Context,
            remoteNotification: RemoteMessage.Notification
        ): Notification {
            // 创建通知
            val channelId = "fcm_notification"
            val channelName = "FCM Notification"
            val notificationManager =
                context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                // 创建通知渠道
                val importance = NotificationManager.IMPORTANCE_DEFAULT
                val channel = NotificationChannel(channelId, channelName, importance)
                notificationManager.createNotificationChannel(channel)
            }

            val intent = Intent(context, SplashActivity::class.java)
            val pendingIntent =
                PendingIntent.getActivity(context, 0, intent, IntentUtil.pendingIntentFlagCompat())
            val notificationBuilder = NotificationCompat.Builder(context, channelId)
                .setSmallIcon(R.drawable.ic_notification_logo)
                .setContentTitle(remoteNotification.title)
                .setContentText(remoteNotification.body)
                .setContentIntent(pendingIntent) // 设置通知点击事件
                .setAutoCancel(true)
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)

            return notificationBuilder.build()
        }

        fun showPromptLocalNotification(context: Context, subCategory: ExploreSubCategory, categoryEventName: String) {
            if (!hasNotificationPermission(context)) {
                return
            }
            val notification = createPromptLocalNotification(context, subCategory, categoryEventName)
            val notificationManager = NotificationManagerCompat.from(context)
            notificationManager.notify(promptLocalNotificationId, notification)
            promptLocalNotificationId++
        }

        private fun createPromptLocalNotification(
            context: Context,
            subCategory: ExploreSubCategory,
            categoryEventName: String
        ): Notification {
            // 创建通知
            val channelId = "prompt_local_notification"
            val channelName = "Prompt Local Notification"
            val notificationManager =
                context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                // 创建通知渠道
                val importance = NotificationManager.IMPORTANCE_DEFAULT
                val channel = NotificationChannel(channelId, channelName, importance)
                notificationManager.createNotificationChannel(channel)
            }

            val intent = Intent(context, ChatActivity::class.java)
            intent.putExtra(EXTRA_FROM_PROMPT_NOTIFICATION, true)
            intent.putExtra(EXTRA_PROMPT_CATEGORY_EVENT_NAME, categoryEventName)
            intent.putExtra(EXTRA_PROMPT_SUBCATEGORY_EVENT_NAME, subCategory.categoryEventName)
            intent.putExtra(KEY_CHAT_PROMPT, subCategory.prompt)
            val stackBuilder = TaskStackBuilder.create(context)
            stackBuilder.addParentStack(ChatActivity::class.java)
            stackBuilder.addNextIntent(intent)
            val pendingIntent =
                stackBuilder.getPendingIntent(promptLocalNotificationId, IntentUtil.pendingIntentFlagCompat())
            val title = subCategory.categoryName + subCategory.emoji
            val notificationBuilder = NotificationCompat.Builder(context, channelId)
                .setSmallIcon(R.drawable.ic_notification_logo)
                .setContentTitle(title)
                .setContentText(subCategory.desc)
                .setContentIntent(pendingIntent) // 设置通知点击事件
                .setAutoCancel(true)
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)

            return notificationBuilder.build()
        }
    }
}